package com.study.springBoot.controller.user;

import com.study.springBoot.domain.User;
import com.study.springBoot.service.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

@Controller
@RequestMapping("/user")
@EnableAutoConfiguration
@PreAuthorize("hasRole('USER')") // Spring Security默认的角色前缀是”ROLE_”,使用hasRole方法时已经默认加上了
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping("")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("user/index");
        return mv;
    }

    @RequestMapping("/insert")
    @ResponseBody
    public void insert(HttpServletRequest request, HttpServletResponse response) {
        Date date = new Date();
        Long nowTime = (date.getTime()) / 1000;

        User u = new User();
        u.setName("ken");
        u.setNickname("ximen");
        u.setPassword("123456");
        u.setInsertTime(nowTime);
        userRepository.save(u);
    }

    @RequestMapping("/info")
    @ResponseBody
    public User info(HttpServletRequest request, HttpServletResponse response, Long id) {
        User u = userRepository.findOne(id);
        System.out.println("userRepository: " + userRepository);
        System.out.println("id: " + id);
        return u;
    }
}
